<?php
require_once 'common.inc';
session_start ();
if (! isset ( $_SESSION ['id'] ) or ! isset ( $_POST ['tname'] ) or ! isset ( $_POST ['start'] ) or ! isset ( $_POST ['limit'] ))
	exit ();
	
	// 检查权限+生成sql
$sql = Array ();
$str = "";
if ($_SESSION ['aboutme'] != '总部用户') {
	$bRight = true;
	switch ($_POST ['tname']) {
		case 'customer' :
		case 'logic' :
		case 'output' :
			// 查看该id所拥有的
			$str = "FROM " . $_POST ['tname'] . " WHERE tmncode in (SELECT tmncode FROM management WHERE id='" . $_SESSION ['id'] . "')";
			break;
		case 'user' :
		case 'management' :
			// 只查看该id的
			$str = "FROM " . $_POST ['tname'] . " WHERE id='" . $_SESSION ['id'] . "'";
			break;
		case 'item' :
		case 'input' :
			// 查看全部
			$str = "FROM " . $_POST ['tname'];
			break;
		default:
			// 不能查看
			$bRight = false;
			break;
	}
	if (! $bRight) {
		echo ("{total:0,root:[]}");
		exit ();
	}
} else {
	$str = "FROM " . $_POST ['tname'];
}

if (isset ( $_POST ['json'] ) && $_POST ['json'] != "") {
	$str2 = "";
	foreach ( json_decode ( $_POST ['json'] ) as $key => $val ) {
		if ($val != "")
			$str2 .= $key . "='" . addslashes ( $val ) . "' AND ";
	}
	if ($str2 != "") {
		if (strpos ( $str, "WHERE" ) === false)
			$str2 = " WHERE " . substr ( $str2, 0, - 5 );
		else
			$str2 = " AND " . substr ( $str2, 0, - 5 );
	}
	$str .= $str2;
}

$sql [0] = "SELECT COUNT(*) " . $str;
$sql [1] = "SELECT * " . $str . " LIMIT " . $_POST ['start'] . "," . $_POST ['limit'];

// 读取数据
$result = execSQL ( $sql [0] );
$count = mysql_result ( $result, 0 );
$result = execSQL ( $sql [1] );
$json = "";
while ( $row = mysql_fetch_array ( $result ) ) {
	$json .= "{";
	foreach ( $row as $key => $val ) {
		if (! is_numeric ( $key ))
			$json .= $key . ":\"" . $val . "\",";
	}
	$json = substr ( $json, 0, - 1 ) . "},";
}
$json = "[" . substr ( $json, 0, - 1 ) . "]";
echo ("{totalProperty:" . $count . ",root:" . $json . "}");
?>